package com.lai.hospital.config;

import com.lai.hospital.filter.JwtAuthenticationFilter;
import com.lai.hospital.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import javax.servlet.Filter;

import static com.lai.hospital.constant.SecurityConst.WHITELIST;

/**
 * @author : lai
 * @version V1.0
 * @Project: hospital-springboot
 * @Package com.lai.hospital.config
 * @Description: Spring Security配置类
 * @date Date : 2022年11月16日 20:46
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint; //认证入口    认证异常

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler; //权限不足处理    授权异常

    @Autowired
    private AuthenticationSuccessHandlerImpl authenticationSuccessHandler;//认证成功处理

    @Autowired
    private AuthenticationFailHandlerImpl authenticationFailHandler;//认证失败处理

    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;//退出成功处理

    @Autowired
    private FilterInvocationSecurityMetadataSourceImpl invocationSecurityMetadataSource;

    @Autowired
    private AccessDecisionManagerImpl accessDecisionManager;

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    //session会话监听器
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置表单登录
        http.formLogin()
                .loginProcessingUrl("/login")//登录url
                .successHandler(authenticationSuccessHandler)//授权成功处理器
                .failureHandler(authenticationFailHandler)//授权失败处理器
                .and()
                .logout()
                .logoutUrl("/logout")//退出url
                .logoutSuccessHandler(logoutSuccessHandler);//配置退出成功处理器
        // 配置路由权限信息
        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O fsi) {
                        fsi.setSecurityMetadataSource(invocationSecurityMetadataSource);//配置元数据
                        fsi.setAccessDecisionManager(accessDecisionManager);//访问决策器
                        return fsi;
                    }
                })
                .antMatchers(WHITELIST).permitAll()//白名单内的路径全部放行
                .anyRequest().authenticated()
                //.anyRequest().permitAll()//其余的全部需要认证
                //.and()
                //设置无状态的连接,即不创建session
                //.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 关闭跨站请求防护
                .csrf().disable().exceptionHandling()
                // 未登录处理
                .authenticationEntryPoint(authenticationEntryPoint)
                // 权限不足处理
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                //TODO 不使用session，在AccessDecisionManager中不能获取到相关的Authentication信息的问题
                .sessionManagement()//session管理器
                .maximumSessions(20)//允许会话的最大并发  一个用户只能在一台设备登录
                .maxSessionsPreventsLogin(false)
                .sessionRegistry(sessionRegistry());//将session交给谁管理;

        //http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }


//    @Bean
//    public Filter jwtAuthenticationFilter() {
//        return new JwtAuthenticationFilter();
//    }
}
